<?php

class myUser extends sfGuardSecurityUser
{
	public $Member = null;
	
	public function initialize(sfEventDispatcher $dispatcher, sfStorage $storage, $options = array()) {
		parent::initialize($dispatcher, $storage, $options);
		sfContext::getInstance()->getLogger()->log('init user', sfLogger::DEBUG);
		
		if($this->isMember()) {
			$this->Member = $this->getProfile()->Member;
		}
	}
	
	public function getMemberId() {
	  if($this->isMember()) {
	    return $this->Member->getId();
	  } else {
	    return 0;
	  }
	}
	
	/**
	 * @return boolean
	 */
	public function isMember() {
		//return true; // TODO adjust
		if(is_null($this->getProfile())) {
			return false; //throw new LogicException();
		}
		return $this->getProfile()->getMemberId() > 0;
	}
	
	/**
	 * @return integer
	 */
	public function getOrganizationalUnitId() {
	    if($id = $this->getProfile()->getOwningOrganizationalUnitId()) {
	      return $id;
	    } elseif($this->isMember()) {
			return $this->Member->getOrganizationalUnitId();
		} else {
			throw new Exception();
		}
	}
	
	/**
	 * @return OrganisationalUnit
	 */
	public function getOrganizationalUnit() {
		if($unit = $this->getProfile()->getOrganizationalUnit()) {
		  return $unit;
		} elseif($this->isMember()) {
		  return $this->Member->getOrganizationalUnit();
		} else {
		  throw new Exception();
		}
	}
	
	public function getOwningOrganizationalUnitIds() {
	  $parent = $this->getOrganizationalUnit();
	  $ids = array(0 => $parent->getId());
	  $units = $parent->getDescendants();
	  foreach($units as $unit) {
	    $ids[] = $unit->getId();
	  }
	  return $ids;
	}
	
	public function getDisplayName() {
	  if($this->isMember()) {
	    return $this->Member->getFirstName().' '.$this->Member->getLastName();
	  } else {
	    return $this->getGuardUser()->getUsername();
	  }
	}
	
	public function isAuthenticated() {
		return parent::isAuthenticated();
	  #return true; // TODO Adjust for production
	}
	
//	public function getGuardUser() {
//		return sfGuardUserTable::getInstance()->findOneByUsername('System');
//	}
}
